package com.example.lenovo.weiyi;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.com.ruanmeng.demon.MusicListM;
import com.com.ruanmeng.demon.VideoListM;
import com.com.ruanmeng.utils.CommonUtil;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import adapter.BaseLoadMoreHeaderAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;
import music.Player;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;

import static music.Player.needxh;

/**
 * 音乐列表
 */
public class MusicListActivity extends BaseActivity implements MediaPlayer.OnCompletionListener {

    @BindView(R.id.rlist_music)
    RecyclerView rlistMusic;
    @BindView(R.id.refresh_music)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.music_progressa)
    SeekBar musicProgressa;
    private LinearLayoutManager linearLayoutManager;
    ArrayList<MusicListM.RowsBean> Temp_list = new ArrayList<>();
    private VideoListAdapter mAdapter;
    private Player player;
    private int page = 1;
    private LinearLayout li_music_null;
    String play_id;//记录正在播放的id

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_list);
        ButterKnife.bind(this);
        ChangLayTitle("音乐");
        LayBack();
        init();
        getData();
    }

    public void init() {
        //空
        li_music_null = (LinearLayout) findViewById(R.id.li_music_null);
        mRefresh.setColorSchemeResources(R.color.MainColor);
        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
            }
        });
        linearLayoutManager = new LinearLayoutManager(this);
        rlistMusic.setLayoutManager(linearLayoutManager);
        mAdapter = new VideoListAdapter(MusicListActivity.this, rlistMusic, Temp_list, R.layout.item_music);
        rlistMusic.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseLoadMoreHeaderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //点击播放音频  变色
//                CommonUtil.showToask(MusicListActivity.this, "click==" + position);
                if (Temp_list.get(position + 1).getCheck() == 1) {
                    for (int i = 0; i < Temp_list.size(); i++) {
                        Temp_list.get(i).setCheck(0);
                    }
                    if (player != null && player.mediaPlayer.isPlaying()) {
                        player.pause();
                        play_id = "";
                    }
                } else {
                    for (int i = 0; i < Temp_list.size(); i++) {
                        Temp_list.get(i).setCheck(0);
                    }
                    Temp_list.get(position + 1).setCheck(1);
                    playvideo(Temp_list.get(position + 1).getLink());
                    play_id = Temp_list.get(position + 1).getCourseId();
                }
                mAdapter.notifyDataSetChanged();


            }
        });
        mAdapter.setOnLoadMoreListener(new BaseLoadMoreHeaderAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                getData();
            }
        });
        //关于音乐
        player = new Player(musicProgressa);
        needxh = 0;//不需要循环播放
        player.mediaPlayer.setOnCompletionListener(this);
    }

    private void getData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.VideoList, Const.POST);
        mRequest.add("fileType", "2");//(1:视频,2音频)
        mRequest.add("page", page);
        CallServer.getRequestInstance().add(MusicListActivity.this, 0, mRequest,
                new CustomHttpListener(MusicListActivity.this, true, MusicListM.class) {

                    @Override
                    public void doWork(Object data, boolean isOne) {
                        MusicListM model = ((MusicListM) data);
                        if (page == 1) {
                            Temp_list.clear();
                        }
                        Temp_list.addAll(model.getRows());
                        if (Temp_list.size() == 0) {
                            li_music_null.setVisibility(View.VISIBLE);
                            rlistMusic.setVisibility(View.GONE);
                        } else {
                            //上拉刷新和下拉加载更多的时候  判断保持播放状态
                            int a = 0;
                            for (int i = 0; i < Temp_list.size(); i++) {
                                if (!TextUtils.isEmpty(play_id) && play_id.equals(Temp_list.get(i).getCourseId())) {
                                    a = 1;
                                    Temp_list.get(i).setCheck(1);
                                }
                            }
                            if (a != 1) {//停止播放
                                if (player != null &&player.mediaPlayer!=null&& player.mediaPlayer.isPlaying()) {
                                    player.pause();
                                }
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        mRefresh.setRefreshing(false);
                    }
                }, true, true);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        for (int i = 0; i < Temp_list.size(); i++) {
            Temp_list.get(i).setCheck(0);
        }
        mAdapter.notifyDataSetChanged();
    }

    public class VideoListAdapter extends BaseLoadMoreHeaderAdapter<MusicListM.RowsBean> {


        public VideoListAdapter(Context mContext, RecyclerView recyclerView, List<MusicListM.RowsBean> mDatas, int mLayoutId) {
            super(mContext, recyclerView, mDatas, mLayoutId);
        }

        @Override
        public void convert(Context mContext, RecyclerView.ViewHolder holder, MusicListM.RowsBean s) {
            LinearLayout li_playmusic = (LinearLayout) holder.itemView.findViewById(R.id.li_playmusic);
            ImageView pic = (ImageView) holder.itemView.findViewById(R.id.imv_musicplay);
            TextView name = (TextView) holder.itemView.findViewById(R.id.tv_music_title);
            TextView tv_music_aditor = (TextView) holder.itemView.findViewById(R.id.tv_music_aditor);
            View li_ban = (View) holder.itemView.findViewById(R.id.view_music_ban);
            View li_man = (View) holder.itemView.findViewById(R.id.view_music_man);
            name.setText(s.getTitle());
            tv_music_aditor.setText(s.getAuthor());
            if (s.getCheck() == 1) {
                name.setTextColor(getResources().getColor(R.color.MainColor));
                pic.setImageResource(R.drawable.zd_music_play_b);
            } else {
                name.setTextColor(getResources().getColor(R.color.FirstGrayColor));
                pic.setImageResource(R.drawable.zd_music_b);
            }
            if (holder.getLayoutPosition() == Temp_list.size() - 1) {
                li_ban.setVisibility(View.GONE);
                li_man.setVisibility(View.VISIBLE);
            } else {
                li_ban.setVisibility(View.VISIBLE);
                li_man.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 关于音乐
     */
    public void playvideo(final String link) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                player.playUrl(HttpIP.Base_IpIMage + link);
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
            player = null;
        }
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        if (player == null) {
            player = new Player(musicProgressa);
        }
    }
}

